package com.quan.system.common.amqp.consumer;

import java.util.Map;

import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.Headers;
import org.springframework.messaging.handler.annotation.Payload;
import org.springframework.stereotype.Component;

import com.quan.common.bean.MailBean;
import com.quan.common.constant.CommonConstant;
import com.quan.common.tools.SendMailUtils;
import com.rabbitmq.client.Channel;

import lombok.extern.slf4j.Slf4j;

/**
 * 消费端-消息队列监听
 * 发送邮件
 * @author yhaoquan
 *
 */
@Slf4j
@Component
public class ConsumerMessageSendMail {

	@Autowired
	private SendMailUtils mailUtils;

	// 配置监听器
	@RabbitListener(
			bindings = @QueueBinding(
					//队列(队列的名称,是否持久化)
					value = @Queue(value = CommonConstant.QUEUE_TOPIC_MAIL, durable = "true"),
					//交换机(交换机的名称,是否持久化,交换机类型)
					exchange = @Exchange(name = CommonConstant.EXCHANGE_TOPIC_MAIL, durable = "true", type = CommonConstant.RABBITMQ_TYPE_TOPIC),
					//队列Routiny Key
					key = CommonConstant.QUEUE_TOPIC_MAIL
			)
	)

	@RabbitHandler
	public void process(@Payload MailBean mailBean, @Headers Map<String, Object> headers, Channel channel)
			throws Exception {
		log.info("==>【RabbitMQ 消息消费端】开始邮件发送消费，队列的名称:{}, 交换机:{}, 路由Key:{}, 消息类型:{}", CommonConstant.QUEUE_TOPIC_MAIL, CommonConstant.EXCHANGE_TOPIC_MAIL, CommonConstant.QUEUE_TOPIC_MAIL, CommonConstant.RABBITMQ_TYPE_TOPIC);

		// 发送邮件
		this.mailUtils.send(mailBean);

		// ACK签收（delivery_tag，是否批量签收）
		channel.basicAck((Long) headers.get(AmqpHeaders.DELIVERY_TAG), false);

	}

}
